package com.yly.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yly.common.response.ResponseVO;
import com.yly.common.util.HttpUtils;
import com.yly.common.vo.LoginUserVO;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 鉴权拦截器
 * @author anqinghang
 * @since 2024/9/18 下午5:16
 */
@Log4j2
@Component
public class AuthInterceptor implements HandlerInterceptor {

  @Value("${auth.checkLogin.url}")
  private String checkLoginUrl;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String token = request.getHeader("token");

    if (token == null || token.isEmpty()) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      response.getWriter().write("Unauthorized: Token is missing");
      return false;
    } else {
      Map<String, Object> params = new HashMap<>();
      params.put("token", token);
      String res = HttpUtils.getInstance().get(checkLoginUrl, 600, params);

      ResponseVO<LoginUserVO> responseVO = JSON.parseObject(res,
          new TypeReference<ResponseVO<LoginUserVO>>() {
          });
      log.info("-----------responseVO:{}", responseVO);

      if (responseVO.getCode() != -1) {
        if (!res.isEmpty()) {
          LoginUserVO loginUserVO = responseVO.getData();

          // 将用户信息放入请求属性
          request.setAttribute("userContext", loginUserVO);
          return true;

          // request.setAttribute("UserId", loginUserVO.getId());
          // request.setAttribute("UserName", loginUserVO.getUsername());
          // request.setAttribute("roleId", loginUserVO.getRoleId().toString());
          // request.setAttribute("groupId", loginUserVO.getGroupId().toString());

        } else {
          // 设置响应状态码为 401 Unauthorized
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          response.getWriter().write("Unauthorized: Token is expire");
          return false;
        }
      } else {
        // 设置响应状态码为 401 Unauthorized
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Unauthorized: Token is error");
        return false;
      }
    }
  }

}
